//
//  NSDate+Extension.swift
//  Micro-blog Sina
//
//  Created by admin on 16/3/30.
//  Copyright © 2016年 admin. All rights reserved.
//

import Foundation

extension NSDate {
    class func sinaDateToDate(string: String) -> NSDate {
        let datefromatter = NSDateFormatter()
        // 设置地区
        datefromatter.locale = NSLocale(localeIdentifier: "EN")
        datefromatter.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy"
        return datefromatter.dateFromString(string) ?? NSDate()
    }
    
    func sinaDateDescription() -> String {
        let calendar = NSCalendar.currentCalendar()
        // 判断是否是当天
        if calendar.isDateInToday(self) {
            // 创建当前时间
            let currentDate = Int(NSDate().timeIntervalSinceDate(self))
            if currentDate < 60 {
                return "刚刚"
            }else if currentDate < 60 * 60 {
                return "\(currentDate / 60)分钟前"
            }else {
                return "\(currentDate / 60 / 60)小时前"
            }
        }
        
        // 日期格式
        var fmt = ""
        // 是否是昨天
        if calendar.isDateInYesterday(self) {
            fmt = "昨天 HH:mm"
        }else if calendar.compareDate(self, toDate: NSDate(), toUnitGranularity: NSCalendarUnit.Year) == NSComparisonResult.OrderedAscending {
            fmt = "yyyy-MM-dd HH:mm"
        }else if calendar.compareDate(self, toDate: NSDate(), toUnitGranularity: NSCalendarUnit.Year) == NSComparisonResult.OrderedSame {
            fmt = "MM-dd HH:mm"
        }
        // 将NSDate转成指定格式的字符串
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = fmt
        dateFormatter.locale = NSLocale(localeIdentifier: "EN")
        return dateFormatter.stringFromDate(self)
    }
}